<template>
  <view class="image-uploader">
    <view class="van-uploader">
      <view
        v-for="(file, index) in fileList"
        :key="index"
        class="van-uploader__preview"
      >
        <image
          :src="formatImgUrl(file.url || file.content)"
          class="van-uploader__preview-image"
          mode="aspectFill"
          @click="onPreview(index)"
        />
        <view
          v-if="!readonly && showDelete"
          class="van-uploader__preview-delete"
          @click.stop="onDelete(index)"
        >
          <van-icon
            name="delete"
            size="26rpx"
            color="#fff"
          />
        </view>
      </view>
      <view
        v-if="!readonly && fileList.length < max"
        class="custom-upload-btn"
        @click="chooseImage"
      >
        <slot>
          <van-icon
            name="photograph"
            size="48rpx"
            color="#0C8D6A"
          />
          <text style="color: #0c8d6a">上传图片</text>
        </slot>
      </view>
    </view>
  </view>
</template>

<script>
  import { formatImgUrl } from '@/common/utils'
  export default {
    name: 'ImageUploader',
    props: {
      value: {
        type: Array,
        default: () => []
      },
      readonly: {
        type: Boolean,
        default: false
      },
      max: {
        type: Number,
        default: 5
      },
      accept: {
        type: Array,
        default: () => ['jpg', 'jpeg', 'png']
      },
      customUpload: {
        type: Function,
        default: null
      },
      showDelete: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        fileList: [...this.value]
      }
    },
    watch: {
      value(val) {
        this.fileList = [...val]
      }
    },
    methods: {
      formatImgUrl,
      chooseImage() {
        const remainCount = this.max - this.fileList.length
        uni.chooseImage({
          count: remainCount,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: async (res) => {
            let files = res.tempFilePaths.map((tempFilePath, index) => ({
              url: tempFilePath,
              content: tempFilePath,
              name: `image_${Date.now()}_${index}.jpg`,
              size: res.tempFiles[index]?.size || 0,
              type: res.tempFiles[index]?.type || 'image/jpeg'
            }))
            // 外部自定义上传逻辑
            if (this.customUpload) {
              files = await Promise.all(
                files.map(async (file) => {
                  const result = await this.customUpload(file)
                  return result || file
                })
              )
            }
            this.fileList = this.fileList.concat(files)
            console.log('this.fileList: ', this.fileList)
            this.$emit('input', this.fileList)
            this.$emit('change', this.fileList)
          },
          fail: (err) => {
            uni.showToast({ title: '选择图片失败', icon: 'none' })
          }
        })
      },
      onPreview(currentIndex) {
        const urls = this.fileList.map((file) => file.url || file.content)
        uni.previewImage({
          current: currentIndex,
          urls: urls
        })
        this.$emit('preview', { index: currentIndex, urls })
      },
      onDelete(index) {
        this.fileList.splice(index, 1)
        this.$emit('input', this.fileList)
        this.$emit('change', this.fileList)
      }
    }
  }
</script>

<style scoped lang="scss">
  .image-uploader {
    width: 100%;
  }
  .van-uploader {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
  }
  .van-uploader__preview {
    position: relative;
    width: 218rpx;
    height: 218rpx;
  }
  .van-uploader__preview-image {
    width: 218rpx;
    height: 218rpx;
    border-radius: 8px;
    object-fit: cover;
    cursor: pointer;
    background: #eee;
  }
  .van-uploader__preview-delete {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
    width: 48rpx;
    height: 48rpx;
    background: #000000;
    border-radius: 0px 10px 0px 0px;
    opacity: 0.8;
  }
  .custom-upload-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 218rpx;
    height: 218rpx;
    background: #f5f5f5;
    border-radius: 8px;
  }
</style>
